<template>
  <div class="content">
    <div class="headBtn">
      <jc-button
        :btn-arr="['reload', 'option']"
        :disab-arr="['close', 'cancel', 'com1', 'com2', 'using', 'freeze']"
        @refresh="handleGetUntreated"
        @toExcel="handleExport"
      />
      <el-button class="btn1" type="primary" size="mini" @click="isdanjuDialog=true">{{ $t('market.putIn') }}</el-button>
      <el-button :loading="deloading" class="btn1" type="danger" size="mini" @click="deleteMO">{{ $t('shop.delete') }}</el-button>
    </div>
    <div class="header">
      <div class="header-name">
        <search :options="selectData" :search-son="searchSon" :msg="tacitly" @seek="collect" @hand="handleQuerySonClass" />
        <el-button type="primary" class="btn" size="mini" @click="handleQuerySonClass">{{ $t('btn.search') }}</el-button>
        <filtration
          :ftype="ftype"
          :msg="tacitly"
          :select-data="selectData"
          :table-header="tableHeader1"
          :detail-header="tableHeader"
          @seachData="handleQuerySonClass"
        />
      </div>
    </div>
    <div class="table-content">
      <jc-table
        v-loading="loading"
        :table-data="tableData"
        :table-header="tableHeader"
        :table-height="tableHeight"
        sortable
        table-selection
        :get-summaries="getSummaries"
        show-summary
        @selectionChange="selectPlan"
      >
        <template v-slot:orderSlot="col">
          <el-link
            type="primary"
            @click="detailPurchase(col.scope.row.fid)"
          >{{ col.scope.row.fbillno }}</el-link>
        </template>
        <!-- 状态 -->
        <template v-slot:billSlot="col">
          <el-tag v-if="col.scope.row.fstatus === '已转'" type="success">{{ $t('market.forwarded') }}</el-tag>
          <el-tag v-if="col.scope.row.fstatus === '未转'" type="danger">{{ $t('market.unconverted') }}</el-tag>
        </template>
        <!--        生产类型-->
        <template v-slot:btnState="col">
          <span v-if="col.scope.row.fstatus === '已转'">{{ col.scope.row.ferpcls }}</span>
          <el-select
            v-else
            v-model="col.scope.row.ferpclsId"
            placeholder="请选择"
            size="mini"
            :disabled="col.scope.row.fstatus === '已转'"
            @change="editLx(col.scope.row)"
          >
            <el-option v-for="item in basicData" :key="item.fid" :label="item.fname" :value="item.fid" />
          </el-select>
        </template>
        <!--        生产部门-->
        <template v-slot:btnSlot="col">
          <span
            v-if="col.scope.row.fstatus === '已转'
              || col.scope.row.ferpclsId === 69"
          >{{ col.scope.row.fworkshop }}</span>
          <el-input
            v-else
            v-model="col.scope.row.fworkshop"
            placeholder="请选择生产部门"
            size="mini"
            :disabled="col.scope.row.fstatus==='已转'"
          >
            <i
              slot="suffix"
              class="el-input__icon el-icon-search"
              @click="handelWorkshop(col.scope.$index)"
            />
          </el-input>
        </template>
        <!--    物料编码    -->
        <template v-slot:text2Slot="col">
          <el-link type="primary" @click="jumpMateriel(col.scope.row)">
            {{ col.scope.row.fnumber }}
          </el-link>
        </template>
        <!--     仓库   -->
        <template v-slot:tagSlot="col">
          <span v-if="col.scope.row.fstatus === '已转'">{{ col.scope.row.fstock }}</span>
          <el-input
            v-else
            v-model="col.scope.row.fstock"
            placeholder="请选择仓库"
            size="mini"
            :disabled="col.scope.row.fstatus==='已转'"
          >
            <i
              slot="suffix"
              class="el-input__icon el-icon-search"
              @click="handleWarehouse(col.scope.row.index)"
            />
          </el-input>
        </template>
        <!--     到货完工日期   -->
        <template v-slot:text3Slot="col">
          <span v-if="col.scope.row.fstatus === '已转'">{{ col.scope.row.fplanfinishdate }}</span>
          <el-date-picker
            v-else
            v-model="col.scope.row.fplanfinishdate"
            type="date"
            value-format="yyyy-MM-dd"
            size="mini"
            @change="planfinHeadel(col.scope.row)"
          />
        </template>
      </jc-table>
      <cardTab @search="handleQueryBomList" />
      <div class="footer">
        <jc-pagination
          :total="total"
          :page.sync="currentPage"
          :limit.sync="size"
          @pagination="handleGetUntreated"
        />
      </div>
    </div>
    <!--  生产部门-->
    <unit v-if="unitVisabled" :msg="funit" @unit="selUnit" />
    <!-- 仓库 -->
    <selectCK v-if="seleceVisiblit" @client="selectCK" />
    <el-dialog
      v-dialogDrag
      model
      :visible.sync="isdanjuDialog"
      :close-on-click-modal="false"
      width="600px"
      top="5vh"
      center
      append-to-body
    >
      <div style="text-align: center;height: 100px;padding: 20px 0;">
        整单合并:
        <el-checkbox v-model="fmerge" style="line-height: 28px">全部分录行一并下推</el-checkbox><br>
        <span style="color: red">备注：仅支持采购申请类的订单合并</span>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="isdanjuDialog = false">{{ $t('btn.cancel') }}</el-button>
        <el-button size="mini" type="primary" @click="InsertMO()">
          {{ $t('btn.confirm') }}
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  queryPlnPlanorderList, updatePlnPlanorder, deletePlnPlanorder, updatePlnPlanorderList
} from '@/api/production/productionList'
import search from '@/components/Search'
import searData from '@/components/Search/mixin'
import { toMxAmina, Forbiders } from '@/components/ToMxamineState'
import { export_json_to_excel, formatJson } from '@/utils/Export2Excel'
import filtration from '@/components/filtration'
import jcButton from '@/components/Button'
import { queryViewItem } from '@/api/marketManage/marketOrder'
import { InsertMO } from '@/api/mrpView'
import bility from '@/mixin/Operability'

export default {
  components: {
    jcButton,
    search,
    filtration,
    cardTab: () => import('@/components/cardTab'),
    unit: () => import('@/views/basic/createMateriel2/components/unit'),
    selectCK: () => import('@/views/production/collect/components/seleceCK')
  },
  mixins: [searData, bility],
  data() {
    return {
      fmerge: false,
      isdanjuDialog: false,
      ftype: 29,
      funit: 'SX_V_WORKSHOP',
      seleteFid: [],
      // 表头
      tableData: [], // 销售数据
      seleceVisiblit: false,
      unitVisabled: false,
      tableHeight: '70vh',
      tableHeader: [
        { label: this.$t('market.coding'), type: 'order', prop: 'fbillno', width: '110' },
        { label: this.$t('shop.state'), type: 'bill', prop: 'fstatus', width: '80' },
        { label: this.$t('market.paezText1'), prop: 'fpaezText', width: '110' },
        { label: this.$t('market.productmolde'), prop: 'productmolde', minWidth: '100' },
        { label: this.$t('market.orderqty'), prop: 'forderqty', width: '100' },
        { label: this.$t('market.salOrder'), prop: 'freleasetype', width: '100' },
        { label: this.$t('market.fmodel'), prop: 'fmodel', minWidth: '120px' },
        { label: this.$t('market.fmaterial'), type: 'text2', prop: 'fnumber', minWidth: '120px', sortable: true },
        { label: this.$t('shop.fname2'), prop: 'fname', minWidth: '120px' },
        { label: this.$t('shop.fspecificaTion'), prop: 'fspecificaTion', minWidth: '120px' },
        { label: this.$t('market.funit'), prop: 'funit', minWidth: '80px' },
        { label: this.$t('market.sourcebillno'), prop: 'fsourcebillno', width: '110' },
        { label: this.$t('market.ferpcls'), type: 'state', prop: 'ferpcls', width: '100' },
        { label: this.$t('market.prodept'), type: 'btn', prop: 'fworkshop', width: '100' },
        { label: this.$t('market.stock2'), type: 'tag', prop: 'fstock', width: '130' },
        { label: this.$t('market.createDate'), prop: 'fcreateDate', width: '130' },
        { label: this.$t('market.aogfinishdate'), type: 'text3', prop: 'fplanfinishdate', width: '120' } //
        // { label: '采购/生产组织', prop: 'fsupplyorg', width: '130' },
        // { label: '结算组织', prop: 'fsettleorg', width: '130' },
        // { label: '入库组织', prop: 'fstockorg', width: '130' },
        // { label: '货主', prop: 'fowner', width: '130' }
      ],
      total: 0,
      size: 200,
      currentPage: 1,
      indexSelf: 0,
      proData: [],
      basicData: [],
      val: [],
      deloading: false,
      seleteAll: [],
      tableHeader1: [
        { label: '建议采购/生产日期', prop: 'fplanstartdate' },
        { label: this.$t('market.creator'), prop: 'fcreator' },
        { label: this.$t('market.cpBillno'), prop: 'productnumber' }
        // { label: this.$t('market.createDate'), prop: 'fcreateDate' }
      ]
    }
  },
  created() {
    this.handleGetUntreated()
    this.getMaterielType()
    this.tableHeader1 = this.tableHeader.concat(this.tableHeader1)
    this.tableHeight = window.innerWidth > 1440 ? 'calc(100vh - 230px)' : '73vh'
  },
  methods: {
    // 导出表格
    handleExport() {
      require.ensure([], () => {
        const tHeader = this.tableHeader.map((res) => {
          return res.label
        })
        const filterVal = this.tableHeader.map((res) => {
          return res.prop
        })
        if (this.tableData.length <= 0) {
          this.$message.warning('没有导出数据')
        } else if (this.val && this.val.length > 0) {
          const list = this.val.map(item => {
            return (toMxAmina(item), Forbiders(item))
          })
          const data = formatJson(filterVal, list)
          export_json_to_excel(tHeader, data, '计划列表')
        } else {
          queryPlnPlanorderList({
            pageNum: 1,
            pageSize: 100000,
            search: this.searCollData
          }).then(res => {
            if (res.code === 0) {
              const list = res.data.array.map(item => {
                return (toMxAmina(item), Forbiders(item))
              })
              const data = formatJson(filterVal, list)
              export_json_to_excel(tHeader, data, '计划列表')
            } else {
              this.$confirm(res.message, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'error'
              })
            }
          })
        }
      })
    },
    // 详情
    detailPurchase(id) {
      this.$router.push(`/planDetails/${id}`)
    },
    // 获取计划列表数据
    async handleGetUntreated(ev) {
      this.loading = true
      this.details = []
      if (ev && !ev.page) {
        this.details = ev
      }
      const DATA = {
        pageNum: this.currentPage,
        pageSize: this.size,
        search: this.searCollData.concat(this.details)
      }
      const RES = await queryPlnPlanorderList(DATA)
      if (RES.code === 0) {
        this.loading = false
        this.tableData = RES.data.array
        this.total = RES.data.total
      } else {
        this.loading = false
        this.$confirm(RES.message, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'error'
        })
      }
    },
    // 搜索
    handleQuerySonClass(ev) {
      this.currentPage = 1
      if (ev && ev.fname) {
        this.searchSon = ev.detail
        this.customHandle(ev)
        this.handleGetUntreated(ev.detail)
      } else {
        this.handleGetUntreated()
      }
    },
    // 成品 原材料
    handleQueryBomList(ev) {
      this.searCollData = []
      this.currentPage = 1
      this.searCollData = ev
      this.searchSon = ev
      this.handleGetUntreated()
    },
    // 确认下发
    async InsertMO() {
      this.selectMrp = []
      this.val.forEach(res => {
        if (res.fstatus === '未转') {
          this.selectMrp.push(res)
        }
      })
      if (this.selectMrp.length === 0) {
        this.$confirm('没有可转订单', '提示', {
          confirmButtonText: '确定',
          type: 'warning'
        })
        return
      }
      const DATA = {
        mrp: this.selectMrp,
        fmerge: this.fmerge
      }
      // for (const item of this.insetData.insert_MoLists) {
      //   if (item.DDLX === '生产订单') {
      //     if (!item.SCBM || !item.StockID) {
      //       this.$confirm('生产部门或仓库不能为空', '提示', {
      //         confirmButtonText: '确定',
      //         type: 'warning'
      //       })
      //       return
      //     }
      //   } else {
      //     if (!item.StockID) {
      //       this.$confirm('仓库不能为空', '提示', {
      //         confirmButtonText: '确定',
      //         type: 'warning'
      //       })
      //       return
      //     }
      //   }
      // }
      this.$confirm('是否确认投放?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        InsertMO(DATA).then(res => {
          if (res.code === 0) {
            this.isdanjuDialog = false
            this.val = []
            this.$message({ showClose: true, message: res.message, type: 'success' })
            this.handleGetUntreated()
          } else {
            this.$confirm(res.message, '提示', {
              confirmButtonText: '确定',
              type: 'warning'
            })
          }
        })
      })
    },
    // 选中行
    selectPlan(val) {
      this.val = val
      this.seleteAll = []
      this.seleteFid = []
      val.forEach(item => {
        this.seleteAll.push(item.fbillno)
        this.seleteFid.push(item.fid)
      })
    },
    // 删除
    deleteMO() {
      this.deloading = true
      const DATA = {
        Numbers: this.seleteAll
      }
      this.$confirm('确定要删除么?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deletePlnPlanorder(DATA).then(res => {
          if (res.code === 0) {
            this.seleteAll = []
            this.innerHTM = ''
            res.data.forEach(res => {
              this.innerHTM += '<div>' + res + '</div>'
            })
            this.$notify.warning({
              title: '提示',
              message: this.innerHTM,
              duration: 3000, offset: 50,
              dangerouslyUseHTMLString: true
            })
            this.handleGetUntreated()
          } else {
            this.$confirm(res.message, '提示', {
              confirmButtonText: '确定',
              type: 'warning'
            })
          }
          this.deloading = false
        })
      })
    },
    // 生产部门
    handelWorkshop(index) {
      this.indexSelf = index
      this.unitVisabled = true
    },
    // 仓库
    handleWarehouse(index) {
      this.indexSelf = index
      this.seleceVisiblit = true
    },
    // 生产部门接受子组件传值
    selUnit(ev) {
      if (ev.fid) {
        const item = this.tableData[this.indexSelf]
        item.fworkshop = ev.fname
        item.fworkshopId = ev.fid
        this.editLx(item)
      }
      this.unitVisabled = false
    },
    // 获取仓库数据
    selectCK(ev) {
      if (ev.fstockId) {
        const item = this.tableData[this.indexSelf]
        item.fstockId = ev.fstockId
        item.fstock = ev.fname
        this.editLx(item)
      }
      this.seleceVisiblit = false
    },
    // 修改生产类型	生产部门	仓库
    editLx(item) {
      const DATA = {
        fid: item.fid,
        ferpclsId: item.ferpclsId,
        fstockId: item.fstockId,
        fworkshopId: item.fworkshopId
      }
      updatePlnPlanorder(DATA).then(res => {
        if (res.code === 0) {
          this.$message({ showClose: true, message: res.message, type: 'success' })
          this.handleGetUntreated()
        } else {
          this.$confirm(res.message, '提示', {
            confirmButtonText: '确定',
            type: 'warning'
          })
        }
      })
    },
    // 修改到货完工日期
    planfinHeadel(ev) {
      const DATA = {
        SourceIds: this.seleteFid.length === 0 ? [ev.fid] : this.seleteFid,
        fplanfinishdate: ev.fplanfinishdate
      }
      updatePlnPlanorderList(DATA).then(res => {
        if (res.code === 0) {
          this.$message({ showClose: true, message: res.message, type: 'success' })
          this.handleGetUntreated()
        } else {
          this.$confirm(res.message, '提示', {
            confirmButtonText: '确定',
            type: 'warning'
          })
        }
      })
    },
    // 获取物料类型
    async getMaterielType() {
      const { data: RES } = await queryViewItem({
        viewName: 'SX_V_UNIT_ERPCLSID'
      })
      this.basicData = RES.list
    },
    // 自定义列表
    customHandle(ev) {
      this.tableHeaders = []
      if (ev.header) {
        ev.header.forEach(item => {
          this.tableHeader1.forEach(res => {
            if (res.label === item) {
              this.tableHeaders.push(res)
            }
          })
        })
        this.tableHeader = this.tableHeaders
      } else if (ev.fname === '缺省方案') {
        this.tableHeader = this.oldTabHeader
      } else {
        this.tableHeader = this.tableHeader1
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.content {
  @include listBom;
  .headBtn {
    display: flex;
    .btn1 {
      margin-left: 10px;
    }
  }
  .header{
    position:relative;
    .header-name{
      width: 100%;
    }
    .btn{
      transform: translateY(18%);
      margin-left: 450px !important;
    }
  }
}
</style>
